package com.wangjw.springbootdemo.interceptor;

import com.wangjw.springbootdemo.pojo.IMoocJSONResult;
import com.wangjw.springbootdemo.utils.JsonUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by wangjw on 18/5/30.
 */
public class TwoInterceptor implements HandlerInterceptor {

    // Controller方法之前调用
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (true) {
            returnErrorResponse(httpServletResponse, IMoocJSONResult.errorMsg("被two拦截..."));
        }
        System.out.println("被two拦截...");
        return false;
    }

    private void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result)
            throws IOException, UnsupportedOperationException {
        try (OutputStream out = response.getOutputStream()) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        }
    }

    // Controller方法之后调用
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    // 整个请求结束之后(主要用于资源清理工作)
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
